<?php
define('SUB_DIR','/services');
session_start();

if(!isset($_SESSION['adm_name']) || empty($_SESSION['adm_name']))
	exit;

//2011-01-30 update
$actions = array('clear','getuser','updategoods','updatesite');
if(isset($_REQUEST['action']))
{
	$action = strtolower($_REQUEST['action']);

	if(!in_array($action,$actions))
		exit;
}
else
	exit;

@set_time_limit(3600);
if(function_exists('ini_set'))
	ini_set('max_execution_time',3600);

require '../core/service/fanwe.service.php';

if($action == 'clear')
{
	$fanwe = &FanweService::instance();
	//2011-01-30 update
	$fanwe->is_admin = true;
	$fanwe->is_session = false;
	$fanwe->is_user = false;
	$fanwe->is_cron = false;
	$fanwe->cache_list = array();
	$fanwe->initialize();

	include_once import('function/cache');
	updateCache();

    clearDir(FANWE_ROOT.'./public/tpl');
	clearDir(FANWE_ROOT.'./admin/Runtime');
	clearDir(FANWE_ROOT.'./update/Runtime');

	include FANWE_ROOT.'./ThinkPHP/Vendor/bbs.php';
	BBSAction::getInstance()->updateSetting();

	$result = array("status"=>1,"info"=>'清除成功',"data"=>"");
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
//2011-01-30 update
elseif($action == 'updategoods')
{
	$fanwe = &FanweService::instance();
	$fanwe->is_admin = true;
	$fanwe->is_session = false;
	$fanwe->is_user = false;
	$fanwe->is_cron = false;
	$fanwe->cache_list = array('goods');
	$fanwe->initialize();

	set_time_limit(0);

	global $_FANWE;

	$begin = isset($_FANWE['request']['begin']) ? intval($_FANWE['request']['begin']) : 0;
	$begin = max($begin,0);

	if($begin == 0)
	{
		DB::query("DELETE FROM ".DB::table('cron')." WHERE type='goods'");
		DB::query("TRUNCATE TABLE ".DB::table('goods_now'));
		DB::query('REPLACE INTO '.DB::table('goods_now').'(id, site_id, site_name, name, city, cate_id, url, click_count, best_count, collect_count, shop_price, market_price, begin_time, end_time, brief, sort, small_img, big_img, score, is_best, bought, collect_buy, ef_time, post_count, r_sort, cr_sort, add_time) SELECT g.id, g.site_id, site_name, name, g.city, g.cate_id, url, click_count, best_count, collect_count, shop_price, market_price, begin_time, g.end_time, brief, g.sort, small_img, big_img, score, is_best, bought, collect_buy, ef_time, post_count, g.r_sort, g.cr_sort, add_time FROM '.DB::table('goods_key').' AS gk INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id WHERE g.status = 1 AND gk.end_time > '.TIME_UTC);

		DB::query("TRUNCATE TABLE ".DB::table('goods_now_key'));
		DB::query('REPLACE INTO '.DB::table('goods_now_key').' SELECT id,site_id,city,cate_id,sort,r_sort,cr_sort,0,0,0,0,end_time FROM '.DB::table('goods_now'));

        DB::query('DELETE FROM '.DB::table('goods_area').' WHERE end_time <= '.TIME_UTC);
		DB::query('DELETE FROM '.DB::table('suppliers').' WHERE end_time <= '.TIME_UTC);
		$delete_ids = array();
		$res = 'SELECT gnm.id 
			FROM '.DB::table('goods_now_match').' AS gnm 
			LEFT JOIN '.DB::table('goods_now_key').' AS gnk ON gnk.id = gnm.id 
			WHERE gnk.id IS NULL';
		while($data = DB::fetch($res))
		{
			$delete_ids[] = $data['id'];
		}
		
		if(count($delete_ids) > 0)
		{
			DB::query('DELETE FROM '.DB::table('goods_now_match').' 
				WHERE id IN ('.implode(',',$delete_ids).')');
		}
		
		DB::query('REPLACE INTO '.DB::table('goods_now_match').' 
            SELECT gm.id,gm.content 
            FROM '.DB::table('goods_now_key').' AS gnk 
            INNER JOIN '.DB::table('goods_match').' AS gm ON gm.id = gnk.id 
            LEFT JOIN '.DB::table('goods_now_match').' AS gnm ON gnm.id = gnk.id 
            WHERE gnm.id IS NULL');

		$begin = 0;
	}

	$sort_sites = array();
	$res = DB::query('SELECT site_id FROM '.DB::table('goods_key').' WHERE end_time > '.getTodayTime().' GROUP BY site_id');
	while($sid = DB::fetch($res))
	{
		$sort_sites[] = $sid['site_id'];
	}

	$data_num = count($sort_sites);
    echo "<script type=\"text/javascript\">document.write('数据表 goods_now 共 ".$data_num." 个站点<br/>');</script>"."\r\n";
    flush();
    ob_flush();

	if($data_num > $begin)
	{
		$site_id = $sort_sites[$begin];

		echo "<script type=\"text/javascript\">document.write('开始更新数据表 goods_now 站点 ".($begin + 1)."<br/>');</script>"."\r\n";
		flush();
		ob_flush();

		DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
		DB::query('REPLACE INTO '.DB::table('goods_temp').'
				SELECT id, site_id, city, cate_id, sort, @sort:=@sort + 1 as r_sort,0,0,0,0,0,end_time
				FROM '.DB::table('goods_now_key').' FORCE INDEX (site),(SELECT @sort:=0) AS t
				WHERE site_id = '.$site_id.' ORDER BY sort ASC,id DESC');

		if(DB::affectedRows() > 0)
		{
			$goods_cate_citys = array();
			$goods_cates = array();
			$goods_citys = array();
			$sql = '';
			$sql_jg = '';
			$res = DB::query('SELECT * FROM '.DB::table('goods_temp').' ORDER BY sort ASC,id DESC');
			while($goods = DB::fetch($res))
			{
				$cr_sort = 0;
				$d_sort = 0;
				$dc_sort = 0;
				$e_sort = 0;
				$ec_sort = 0;

				$city = $goods['city'];
				if(!isset($goods_citys[$city]))
					$goods_citys[$city] = 0;
				$goods_citys[$city]++;
				$cr_sort = $goods_citys[$city];

				$cate_id = $goods['cate_id'];
				$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
				if(!isset($goods_cates[$cate_id]))
					$goods_cates[$cate_id] = 0;
				$goods_cates[$cate_id]++;

				if(!isset($goods_cate_citys[$cate_id][$city]))
					$goods_cate_citys[$cate_id][$city] = 0;
				$goods_cate_citys[$cate_id][$city]++;

				$parent_id = $cate['pid'];
				if($parent_id > 0)
				{
					$e_sort = $goods_cates[$cate_id];
					$ec_sort = $goods_cate_citys[$cate_id][$city];

					if(!isset($goods_cates[$parent_id]))
						$goods_cates[$parent_id] = 0;
					$goods_cates[$parent_id]++;

					$d_sort = $goods_cates[$parent_id];

					if(!isset($goods_cate_citys[$parent_id][$city]))
						$goods_cate_citys[$parent_id][$city] = 0;
					$goods_cate_citys[$parent_id][$city]++;

					$dc_sort = $goods_cate_citys[$parent_id][$city];
				}
				else
				{
					$d_sort = $goods_cates[$cate_id];
					$dc_sort = $goods_cate_citys[$cate_id][$city];
				}

				$sql .= "$sql_jg($goods[id],$goods[site_id], '$city', $cate_id, $goods[sort], $goods[r_sort], $cr_sort, $d_sort, $dc_sort, $e_sort, $ec_sort, $goods[end_time])";
				$sql_jg = ',';
			}

			if($sql != '')
			{
				DB::query('REPLACE INTO '.DB::table('goods_temp').' VALUES '.$sql);
				DB::query('REPLACE INTO '.DB::table('goods_now_key').' SELECT * FROM '.DB::table('goods_temp'));
			}
		}

		usleep(10);
		DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
		DB::query('REPLACE INTO '.DB::table('goods_temp').'
				SELECT id, site_id, city, cate_id, sort, @sort:=@sort + 1 as r_sort,0,0,0,0,0,end_time
				FROM '.DB::table('goods_key').' FORCE INDEX (site),(SELECT @sort:=0) AS t
				WHERE site_id = '.$site_id.' AND end_time > '.getTodayTime().'
				ORDER BY sort ASC,id DESC');
		if(DB::affectedRows() > 0)
		{
			$goods_cate_citys = array();
			$goods_cates = array();
			$goods_citys = array();
			$sql = '';
			$sql_jg = '';
			$res = DB::query('SELECT * FROM '.DB::table('goods_temp').' ORDER BY sort ASC,id DESC');
			while($goods = DB::fetch($res))
			{
				$cr_sort = 0;
				$d_sort = 0;
				$dc_sort = 0;
				$e_sort = 0;
				$ec_sort = 0;

				$city = $goods['city'];
				if(!isset($goods_citys[$city]))
					$goods_citys[$city] = 0;
				$goods_citys[$city]++;
				$cr_sort = $goods_citys[$city];

				$cate_id = $goods['cate_id'];
				$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
				if(!isset($goods_cates[$cate_id]))
					$goods_cates[$cate_id] = 0;
				$goods_cates[$cate_id]++;

				if(!isset($goods_cate_citys[$cate_id][$city]))
					$goods_cate_citys[$cate_id][$city] = 0;
				$goods_cate_citys[$cate_id][$city]++;

				$parent_id = $cate['pid'];
				if($parent_id > 0)
				{
					$e_sort = $goods_cates[$cate_id];
					$ec_sort = $goods_cate_citys[$cate_id][$city];

					if(!isset($goods_cates[$parent_id]))
						$goods_cates[$parent_id] = 0;
					$goods_cates[$parent_id]++;

					$d_sort = $goods_cates[$parent_id];

					if(!isset($goods_cate_citys[$parent_id][$city]))
						$goods_cate_citys[$parent_id][$city] = 0;
					$goods_cate_citys[$parent_id][$city]++;

					$dc_sort = $goods_cate_citys[$parent_id][$city];
				}
				else
				{
					$d_sort = $goods_cates[$cate_id];
					$dc_sort = $goods_cate_citys[$cate_id][$city];
				}

				$sql .= "$sql_jg($goods[id],$goods[site_id], '$city', $cate_id, $goods[sort], $goods[r_sort], $cr_sort, $d_sort, $dc_sort, $e_sort, $ec_sort, $goods[end_time])";
				$sql_jg = ',';
			}

			if($sql != '')
			{
				DB::query('REPLACE INTO '.DB::table('goods_temp').' VALUES '.$sql);
				DB::query('REPLACE INTO '.DB::table('goods_key').' SELECT * FROM '.DB::table('goods_temp'));
			}
		}

		echo "<script type=\"text/javascript\">document.write('更新数据表 goods_now　站点 ".($begin + 1)." 成功<br/>');</script>"."\r\n";
		flush();
		ob_flush();

		echo "<script type=\"text/javascript\">var fun = function(){location.href='admin.php?action=updategoods&begin=".($begin + 1)."';}; setTimeout(fun,500);</script>"."\r\n";
		flush();
		ob_flush();
		exit;
	}
	else
	{
		DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
		S('Goods')->updateAuctionRank();
		echo "<script type=\"text/javascript\">document.write('<br/>更新成功');</script>"."\r\n";
		flush();
		ob_flush();
		exit;
	}
}
elseif($action == 'updatesite')
{
	$fanwe = &FanweService::instance();
	$fanwe->is_admin = true;
	$fanwe->is_session = false;
	$fanwe->is_user = false;
	$fanwe->is_cron = false;
	$fanwe->cache_list = array('goods');
	$fanwe->initialize();

	set_time_limit(0);

	global $_FANWE;

	$begin = isset($_FANWE['request']['begin']) ? intval($_FANWE['request']['begin']) : 0;
	$begin = max($begin,0);

	$site_id = intval($_FANWE['request']['id']);

	echo "<script type=\"text/javascript\">document.write('开始更新数据表 goods_now 站点 ".$site_id."<br/>');</script>"."\r\n";
	flush();
	ob_flush();

	DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
	DB::query('REPLACE INTO '.DB::table('goods_temp').'
			SELECT id, site_id, city, cate_id, sort, @sort:=@sort + 1 as r_sort,0,0,0,0,0,end_time
			FROM '.DB::table('goods_now_key').' FORCE INDEX (site),(SELECT @sort:=0) AS t
			WHERE site_id = '.$site_id.' ORDER BY sort ASC,id DESC');

	if(DB::affectedRows() > 0)
	{
		$goods_cate_citys = array();
		$goods_cates = array();
		$goods_citys = array();
		$sql = '';
		$sql_jg = '';
		$res = DB::query('SELECT * FROM '.DB::table('goods_temp').' ORDER BY sort ASC,id DESC');
		while($goods = DB::fetch($res))
		{
			$cr_sort = 0;
			$d_sort = 0;
			$dc_sort = 0;
			$e_sort = 0;
			$ec_sort = 0;

			$city = $goods['city'];
			if(!isset($goods_citys[$city]))
				$goods_citys[$city] = 0;
			$goods_citys[$city]++;
			$cr_sort = $goods_citys[$city];

			$cate_id = $goods['cate_id'];
			$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
			if(!isset($goods_cates[$cate_id]))
				$goods_cates[$cate_id] = 0;
			$goods_cates[$cate_id]++;

			if(!isset($goods_cate_citys[$cate_id][$city]))
				$goods_cate_citys[$cate_id][$city] = 0;
			$goods_cate_citys[$cate_id][$city]++;

			$parent_id = $cate['pid'];
			if($parent_id > 0)
			{
				$e_sort = $goods_cates[$cate_id];
				$ec_sort = $goods_cate_citys[$cate_id][$city];

				if(!isset($goods_cates[$parent_id]))
					$goods_cates[$parent_id] = 0;
				$goods_cates[$parent_id]++;

				$d_sort = $goods_cates[$parent_id];

				if(!isset($goods_cate_citys[$parent_id][$city]))
					$goods_cate_citys[$parent_id][$city] = 0;
				$goods_cate_citys[$parent_id][$city]++;

				$dc_sort = $goods_cate_citys[$parent_id][$city];
			}
			else
			{
				$d_sort = $goods_cates[$cate_id];
				$dc_sort = $goods_cate_citys[$cate_id][$city];
			}

			$sql .= "$sql_jg($goods[id],$goods[site_id], '$city', $cate_id, $goods[sort], $goods[r_sort], $cr_sort, $d_sort, $dc_sort, $e_sort, $ec_sort, $goods[end_time])";
			$sql_jg = ',';
		}

		if($sql != '')
		{
			DB::query('REPLACE INTO '.DB::table('goods_temp').' VALUES '.$sql);
			DB::query('REPLACE INTO '.DB::table('goods_now_key').' SELECT * FROM '.DB::table('goods_temp'));
		}
	}

	usleep(10);
	DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
	DB::query('REPLACE INTO '.DB::table('goods_temp').'
			SELECT id, site_id, city, cate_id, sort, @sort:=@sort + 1 as r_sort,0,0,0,0,0,end_time
			FROM '.DB::table('goods_key').' FORCE INDEX (site),(SELECT @sort:=0) AS t
			WHERE site_id = '.$site_id.' AND end_time > '.getTodayTime().'
			ORDER BY sort ASC,id DESC');
	if(DB::affectedRows() > 0)
	{
		$goods_cate_citys = array();
		$goods_cates = array();
		$goods_citys = array();
		$sql = '';
		$sql_jg = '';
		$res = DB::query('SELECT * FROM '.DB::table('goods_temp').' ORDER BY sort ASC,id DESC');
		while($goods = DB::fetch($res))
		{
			$cr_sort = 0;
			$d_sort = 0;
			$dc_sort = 0;
			$e_sort = 0;
			$ec_sort = 0;

			$city = $goods['city'];
			if(!isset($goods_citys[$city]))
				$goods_citys[$city] = 0;
			$goods_citys[$city]++;
			$cr_sort = $goods_citys[$city];

			$cate_id = $goods['cate_id'];
			$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
			if(!isset($goods_cates[$cate_id]))
				$goods_cates[$cate_id] = 0;
			$goods_cates[$cate_id]++;

			if(!isset($goods_cate_citys[$cate_id][$city]))
				$goods_cate_citys[$cate_id][$city] = 0;
			$goods_cate_citys[$cate_id][$city]++;

			$parent_id = $cate['pid'];
			if($parent_id > 0)
			{
				$e_sort = $goods_cates[$cate_id];
				$ec_sort = $goods_cate_citys[$cate_id][$city];

				if(!isset($goods_cates[$parent_id]))
					$goods_cates[$parent_id] = 0;
				$goods_cates[$parent_id]++;

				$d_sort = $goods_cates[$parent_id];

				if(!isset($goods_cate_citys[$parent_id][$city]))
					$goods_cate_citys[$parent_id][$city] = 0;
				$goods_cate_citys[$parent_id][$city]++;

				$dc_sort = $goods_cate_citys[$parent_id][$city];
			}
			else
			{
				$d_sort = $goods_cates[$cate_id];
				$dc_sort = $goods_cate_citys[$cate_id][$city];
			}

			$sql .= "$sql_jg($goods[id],$goods[site_id], '$city', $cate_id, $goods[sort], $goods[r_sort], $cr_sort, $d_sort, $dc_sort, $e_sort, $ec_sort, $goods[end_time])";
			$sql_jg = ',';
		}

		if($sql != '')
		{
			DB::query('REPLACE INTO '.DB::table('goods_temp').' VALUES '.$sql);
			DB::query('REPLACE INTO '.DB::table('goods_key').' SELECT * FROM '.DB::table('goods_temp'));
		}
	}

	DB::query('TRUNCATE TABLE '.DB::table('goods_temp'));
	S('Goods')->updateAuctionRank();
	echo "<script type=\"text/javascript\">document.write('<br/>更新成功');</script>"."\r\n";
	flush();
	ob_flush();
	exit;
}
elseif($action == 'getuser')
{
	$fanwe = &FanweService::instance();
	//2011-01-30 update
	$fanwe->is_admin = true;
	$fanwe->cache_list = array();
	$fanwe->initialize();

	$where = 'status >= 0';
	$is_site = intval($fanwe->var['request']['is_site']);
	$user_key = trim($fanwe->var['request']['user_key']);
	if($is_site == 1)
		$where.=' AND groupid = '.SITE_USER_GROUP_ID;

	if($user_key <> '')
	{
		$user_key = '%'.mysqlLikeQuote($user_key).'%';
		$where.=" AND (username LIKE '$user_key' OR email LIKE '$user_key')";
	}

	$query = DB::query('SELECT uid,username FROM '.DB::table('common_member').' WHERE '.$where.' ORDER BY uid DESC LIMIT 0,30');
	$users = array();
	while($user = DB::fetch($query))
	{
		$users[] = $user;
	}

	include import('class/json');
	$json = new JSON();
	die($json->encode($users));
}
?>